package pers.qianyu.auth.service;

import com.alibaba.fastjson.*;
import com.google.common.collect.*;
import lombok.extern.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.*;
import org.springframework.security.crypto.bcrypt.*;
import org.springframework.stereotype.*;
import pers.qianyu.auth.pojo.entity.*;
import pers.qianyu.auth.repository.*;

/**
 * @author mizzle rain
 * @date 2020-10-25 12:34
 */
@Slf4j
@Component
public class InitUserService implements CommandLineRunner {
    @Autowired
    private UserRepository userRepository;

    @Override
    public void run(String... args) throws Exception {
        if (userRepository.findByUsername("admin").isPresent()) {
            return;
        }
        AuthorityPO add = new AuthorityPO();
        add.setName("user:add");
        AuthorityPO delete = new AuthorityPO();
        delete.setName("user:delete");
        AuthorityPO update = new AuthorityPO();
        update.setName("user:update");
        AuthorityPO query = new AuthorityPO();
        query.setName("user:query");

        RolePO rolePO = new RolePO();
        rolePO.setAuthorities(Sets.newHashSet(add, delete, update, query));
        rolePO.setName("ADMIN");

        UserPO userPO = new UserPO();
        userPO.setRoles(Sets.newHashSet(rolePO));
        userPO.setUsername("admin");
        userPO.setPassword(BCrypt.hashpw("hgUHJQ1p9N", BCrypt.gensalt()));
        userPO.setStatus(1);

        userRepository.save(userPO);
        log.info("自动创建管理员用户......\n{}", JSON.toJSONString(userPO, true));
    }
}
